<template>
  <div class="page-container">
    <div v-if="loading" class="loading-overlay">
        <div class="loading-spinner"></div>
        <div class="loading-text">加载中，请稍候...</div>
    </div>

    <!-- 奖品库存列表 -->
    <div class="project-table">
      <div class="table-header">
        <div class="table-title">奖品库存列表</div>
        <div class="table-actions">
          <div class="create-button" @click="openInventoryForm">添加库存</div>
        </div>
      </div>
      <el-scrollbar style="margin-bottom: 20px" height="980px">
        <el-table
          :data="verificationList"
          style="width: 100%"
          :header-cell-style="{
            'text-align': 'center',
            height: '50px',
            color: '#999999',
            'font-size': '15px',
          }"
          :cell-style="{ 'text-align': 'center', height: '70px' }"
        >
          <el-table-column prop="pid" label="体验项目名称">
            <template #default="scope">
              <span>{{ getProjectName(scope.row.pid) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="gid" label="礼品名称">
            <template #default="scope">
              <span>{{ getGiftName(scope.row.gid) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="stock_type" label="库存类型">
            <template #default="scope">
              {{ getInventoryTypeName(scope.row.stock_type) }}
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存数量" />
          <!-- 修改开始时间列 -->
          <el-table-column label="开始时间">
            <template #default="scope">
              {{ scope.row.stock_type === 1 ? scope.row.start_time : '-' }}
            </template>
          </el-table-column>
          
          <!-- 修改结束时间列 -->
          <el-table-column label="结束时间">
            <template #default="scope">
              {{ scope.row.stock_type === 1 ? scope.row.end_time : '-' }}
            </template>
          </el-table-column>
          <!-- 新增时间段范围列 -->
          <!-- 日期列 -->
          <el-table-column label="日期">
            <template #default="scope">
              {{ formatTimeRange(scope.row).split(' ')[0] }}
            </template>
          </el-table-column>
          <!-- 时间段列 -->
          <el-table-column label="时间段">
            <template #default="scope">
              {{ formatTimeRange(scope.row).split(' ')[1] }}
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              <el-tag :type="scope.row.status ? 'success' : 'info'">
                {{ scope.row.status ? "启用" : "停用" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="text" @click="handleEdit(scope.row)"
                >编辑</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </div>

    <!-- 库存表单弹窗 -->
    <el-dialog
      v-model="inventoryFormVisible"
      :title="isEdit ? '编辑库存' : '添加库存'"
      width="700px"
      :before-close="() => handleClose('inventory')"
      class="fullscreen-center-dialog"
    >
      <el-form
        ref="inventoryFormRef"
        :model="inventoryForm"
        :rules="inventoryFormRules"
        label-width="140px"
        size="default"
      >
        <!-- 关联项目 -->
        <el-form-item label="体验项目" prop="pid">
          <el-select
            v-model="inventoryForm.pid"
            placeholder="请选择体验项目"
            clearable
            filterable
            class="w-full"
          >
            <el-option
              v-for="item in projectList"
              :key="item.pid"
              :label="item.pname"
              :value="item.pid"
            />
          </el-select>
        </el-form-item>

        <!-- 关联礼品 -->
        <el-form-item label="选择礼品" prop="gid">
          <el-select
            v-model="inventoryForm.gid"
            placeholder="请选择礼品"
            clearable
            filterable
            class="w-full"
          >
            <el-option
              v-for="gift in giftBagList"
              :key="gift.id"
              :label="gift.gname"
              :value="gift.id"
            />
          </el-select>
        </el-form-item>

        <!-- 库存类型 -->
        <el-form-item label="库存类型" prop="stock_type">
          <el-radio-group v-model="inventoryForm.stock_type" size="large">
            <el-radio :label="1" class="custom-radio">整个展期库存</el-radio>
            <el-radio :label="2" class="custom-radio">每天库存</el-radio>
            <el-radio :label="3" class="custom-radio"
              >时间段库存</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <!-- 库存数量 -->
        <el-form-item label="库存数量" prop="stock">
          <el-input-number
            v-model="inventoryForm.stock"
            :min="0"
            :max="20000"
            step-strictly
            placeholder="0-20000之间的整数"
            class="custom-number-input"
          />
        </el-form-item>

        <!-- 开始时间 -->
        <el-form-item label="开始时间" prop="start_time">
          <el-date-picker
            v-model="inventoryForm.start_time"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="() => {
              inventoryFormRef.value?.validateField('start_time');
              inventoryFormRef.value?.validateField('end_time');
            }"
          />
        </el-form-item>

        <!-- 结束时间 -->
        <el-form-item label="结束时间" prop="end_time">
          <el-date-picker
            v-model="inventoryForm.end_time"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <!-- 是否停用 -->
        <el-form-item label="是否停用" prop="status">
          <el-switch
            v-model="inventoryForm.status"
            active-text="启用"
            inactive-text="停用"
            :active-value="1"
            :inactive-value="0"
            active-color="#34d399"
            inactive-color="#f87171"
            class="custom-switch"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button
          @click="handleClose('inventory')"
          class="custom-button cancel-button"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="submitInventoryForm"
          class="custom-button confirm-button"
          >{{ isEdit ? '确认更新' : '确认添加' }}</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import http from "@/libs/http";
import { useRoute } from "vue-router";
const route = useRoute();

const showGiftDialog = ref(false);
const inventoryFormVisible = ref(false);
const isEdit = ref(false);
const inventoryFormRef = ref(null);
const projectList = ref([]); //项目列表数组项
const giftBagList = ref([]); //礼品列表
const loading = ref(false);

const inventoryForm = reactive({
  id: 0,
  pid: '',
  gid: '',
  stock_type: 1,
  stock: 0,
  start_time: "",
  end_time: "",
  status: 1,
});

const inventoryFormRules = ref({
    end_time: [
      { required: true, message: '请选择结束时间', trigger: 'change' },
      {
        validator: (rule, value, callback) => {
          if (!value) return callback(new Error('请选择结束时间'));
          if (!inventoryForm.start_time) return callback();
          const endDate = new Date(value);
          const startDate = new Date(inventoryForm.start_time);
          if (isNaN(endDate.getTime()) || isNaN(startDate.getTime())) {
            return callback(new Error('日期格式不正确'));
          }
          if (endDate < startDate) {
            callback(new Error('结束时间不能早于开始时间'));
          } else {
            callback();
          }
        },
        trigger: ['change', 'blur']
      }
    ],
  pid: [
    { required: true, message: "请选择体验项目", trigger: "change" }
  ],
  gid: [
    { required: true, message: "请选择礼品", trigger: "change" }
  ],
  stock_type: [
    { required: true, message: "请选择库存类型", trigger: "change" },
  ],
  stock: [
    { required: true, message: "请输入库存数量", trigger: "blur" },
    {
      type: "number",
      min: 0,
      max: 20000,
      message: "请输入0-20000之间的整数",
      trigger: "change",
    },
  ],
  start_time: [
      { required: true, message: "请选择开始时间", trigger: "change" },
      {
        validator: (rule, value, callback) => {
          if (value && inventoryForm.end_time && new Date(value).getTime() >= new Date(inventoryForm.end_time).getTime()) {
            inventoryFormRef.value?.validateField('end_time');
          }
          callback();
        },
        trigger: 'change'
      }
    ],
});

const openInventoryForm = () => {
  isEdit.value = false;
  resetInventoryForm(); // 创建表单时重置
  inventoryFormVisible.value = true;
};

//通过站点的ID,去获取站点的体验项目ID
const getProjectID = async () => {
  try {
    const param = {
      token: localStorage.getItem("openid"),
      activity_id: Number(route.query.site),
    };
    const { code, data } = await http.$post(
      "/hd_project/Backend/getProjectList",
      param
    );
    if (code == 200) {
      // 抽离pid和pname组成新数组
      projectList.value = data.map((item) => ({
        pid: item.id,
        pname: item.play_name,
      }));
      console.log(">>>>>>>>>>>>>拿到项目体验项目数据", projectList.value);
    } else {
      console.log(">>>>>>>>>获取失败");
    }
  } catch (error) {
    ElMessage.error("获取礼品列表失败");
  }
};
// 获取礼品列表
const getGiftList = async () => {
  try {
    const param = {
      token: localStorage.getItem("openid"),
      activity_id: Number(route.query.site),
    };
    const { code, data } = await http.$post(
      "/hd_project/Backend/getGiftLift",
      param
    );
    if (code == 200) {
      // 循环抽离id和gname字段创建新数组
      const newArray = data.map((item) => ({
        id: item.id,
        gname: item.gname,
      }));
      giftBagList.value = newArray;
      console.log('>>>>>>>>拿到礼品列表', giftBagList.value)
    } else {
      console.log(">>>>>>>>>获取失败");
    }
  } catch (error) {
    ElMessage.error("获取礼品列表失败");
  }
};

// 获取礼品库存列表
const getGiftStockList = async () => {
    try {
    const param = {
      token: localStorage.getItem("openid"),
      activity_id: Number(route.query.site),
      pid: 0,
      gid: 0
    };
    loading.value = true;
    const { code, data } = await http.$post(
      "/hd_project/Backend/getGiftStockList",
      param
    );
    if (code == 200) {
      loading.value = false;
      verificationList.value = data
      console.log('>>>>>>>>拿到库存列表数据', data)
    } else {
      loading.value = false;
      console.log(">>>>>>>>>获取失败");
    }
  } catch (error) {
    loading.value = false;
    ElMessage.error("获取礼品列表失败");
  }
};


const submitInventoryForm = async () => {
  try {
        await inventoryFormRef.value.validate();
        // 准备提交数据，映射参数名称
        const params = {
          token: localStorage.getItem("openid"),
          activity_id: Number(route.query.site),
          id: isEdit.value ? inventoryForm.id : 0,
          ...inventoryForm,
        };
        console.log(params, '>>>>>>>>>>>>>>>>提交的表达数据')
        
        if (isEdit.value) {
          // 编辑逻辑
          try {
            const { code } = await http.$post('/hd_project/Backend/editGiftStockDetail', params);
            if (code === 200) {
              ElMessage.success("库存更新成功");
              getGiftStockList()
            } else {
              ElMessage.error('更新失败');
            }
          } catch (error) {
            ElMessage.error('请求异常，请重试');
          }
        } else {
          // 添加逻辑
          try {
            const { code } = await http.$post('/hd_project/Backend/editGiftStockDetail', params);
            if (code === 200) {
              ElMessage.success("库存添加成功");
              getGiftStockList()
            } else {
              ElMessage.error('添加失败');
            }
          } catch (error) {
            ElMessage.error('请求异常，请重试');
          }
        }
        inventoryFormVisible.value = false;
        resetInventoryForm(); // 提交成功后重置
      } catch (error) {
        ElMessage.error("表单验证失败，请检查填写内容");
      }
};

const handleEdit = (row) => {
  resetInventoryForm(); // 先重置
  isEdit.value = true; // 再设置编辑状态
  Object.assign(inventoryForm, row);
  inventoryFormVisible.value = true;
};

const resetInventoryForm = () => {
  if (inventoryFormRef.value) {
    inventoryFormRef.value.resetFields();
  }
  Object.assign(inventoryForm, {
    id: 0,
    pid: '',
    gid: '',
    stock_type: 1,
    stock: 0,
    start_time: '',
    end_time: '',
    status: 1
  });
  // 移除这行: isEdit.value = false;
};

const handleClose = (formType) => {
  if (formType === "inventory") {
    inventoryFormVisible.value = false;
    resetInventoryForm(); // 关闭表单时重置
  } else {
    showGiftDialog.value = false;
  }
};

const getProjectName = (pid) => {
  const project = projectList.value.find(item => item.pid === pid);
  return project ? project.pname : '';
};

const getGiftName = (gid) => {
  const gift = giftBagList.value.find(item => item.id === gid);
  return gift ? gift.gname : '';
};

const getInventoryTypeName = (type) => {
  const typeMap = {
    1: "整个展期库存",
    2: "每天库存",
    3: "时间段库存",
  };
  return typeMap[type] || type;
};

const verificationList = ref([]);

// 初始化
onMounted(() => {
    getGiftStockList()
    getGiftList();
    getProjectID();
});

// 格式化时间段范围
const formatTimeRange = (row) => {
  // 库存类型为每天库存(2)或时间段库存(3)时显示时间范围
  if ([2, 3].includes(row.stock_type) && row.start_time && row.end_time) {
    const [startDate, startTime] = row.start_time.split(' ');
    const [endDate, endTime] = row.end_time.split(' ');
    // 日期相同则只显示一次日期
    return startDate === endDate
      ? `${startDate} ${startTime}-${endTime}`
      : `${row.start_time}-${row.end_time}`;
  }
  // 整个展期库存(1)显示'-'
  return '-';
};
</script>

<style scoped>
.upload-tip-wrap {
  white-space: normal;
  word-wrap: break-word;
  max-width: 100%;
}
.custom-button {
  padding: 12px 24px;
  font-size: 16px;
  border-radius: 8px;
  font-weight: bold;
}

.cancel-button {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e4e4 100%);
  border: 1px solid #dcdcdc;
  color: #333;
}

.confirm-button {
  background: linear-gradient(135deg, #409eff 0%, #2979ff 100%);
  border: none;
  color: #fff;
}

.confirm-button:hover {
  background: linear-gradient(135deg, #3a8ee6 0%, #2370db 100%);
}
.custom-radio {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e4e4 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border-radius: 4px;
  padding: 6px 12px;
  margin-right: 12px;
}

.custom-radio.is-checked {
  background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}
.custom-number-input {
  --el-input-bg-color: rgba(255, 255, 255, 0.85);
  --el-input-border-color: #e4e7ed;
  --el-input-text-color: #303133;
  --el-input-hover-bg-color: rgba(255, 255, 255, 0.95);
  --el-input-focus-bg-color: #ffffff;
  --el-input-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  --el-input-focus-shadow: 0 0 0 2px rgba(144, 147, 153, 0.2);
  --el-input-btn-bg-color: #f2f3f5;
  --el-input-btn-hover-bg-color: #e6e6e6;
}

.custom-number-input .el-input__wrapper {
  background-color: var(--el-input-bg-color);
  border-radius: 8px;
  box-shadow: var(--el-input-shadow);
  transition: all 0.3s ease;
}

.custom-number-input .el-input__wrapper:hover {
  background-color: var(--el-input-hover-bg-color);
  border-color: var(--el-input-border-color);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.custom-number-input .el-input__wrapper:focus-within {
  background-color: var(--el-input-focus-bg-color);
  border-color: #4096ff;
  box-shadow: var(--el-input-focus-shadow), 0 4px 12px rgba(0, 0, 0, 0.1);
}

.custom-number-input .el-input__suffix {
  padding-right: 8px;
}

.custom-number-input .el-input-number__decrease,
.custom-number-input .el-input-number__increase {
  width: 32px;
  height: 100%;
  background-color: var(--el-input-btn-bg-color);
  border-radius: 0;
  transition: all 0.2s ease;
}

.custom-number-input .el-input-number__decrease:hover,
.custom-number-input .el-input-number__increase:hover {
  background-color: var(--el-input-btn-hover-bg-color);
}

.custom-number-input .el-input-number__decrease {
  border-top-left-radius: 8px;
  border-bottom-left-radius: 8px;
}

.custom-number-input .el-input-number__increase {
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
}

.custom-number-input .el-input-number__decrease.is-disabled,
.custom-number-input .el-input-number__increase.is-disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(64, 150, 255, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(64, 150, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(64, 150, 255, 0);
  }
}

.custom-number-input .el-input__wrapper:focus-within {
  animation: pulse 0.6s;
}

.upload-button-container {
  display: flex;
  flex-direction: column;
}

.upload-button {
  width: 80px;
  height: 80px;
  border: 2px dashed #dcdcdc;
  border-radius: 4px;
  background-color: #f8f8f8;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-button:hover {
  border-color: #4096ff;
  background-color: #e6f7ff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.upload-plus {
  font-size: 32px;
  color: #909399;
  font-weight: bold;
}

.upload-text {
  margin-top: 10px;
  font-size: 14px;
  color: #909399;
}

.custom-switch {
  --switch-width: 60px;
  --switch-height: 30px;
  --switch-border-radius: 15px;
  --switch-padding: 3px;
  --switch-transition: all 0.3s ease;
}

.custom-switch .el-switch__core {
  width: var(--switch-width);
  height: var(--switch-height);
  border-radius: var(--switch-border-radius);
  padding: var(--switch-padding);
  transition: var(--switch-transition);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.custom-switch .el-switch__core:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.custom-switch .el-switch__core .el-switch__button {
  width: calc(var(--switch-height) - 2 * var(--switch-padding));
  height: calc(var(--switch-height) - 2 * var(--switch-padding));
  border-radius: 50%;
  transition: var(--switch-transition);
}

.custom-switch .el-switch__core.is-active .el-switch__button {
  transform: translateX(calc(var(--switch-width) - var(--switch-height)));
  animation: pulse 0.5s;
}

.custom-switch .el-switch__label {
  font-size: 14px;
  font-weight: 500;
  padding: 0 10px;
}

.custom-switch .el-switch__label.is-active {
  color: #10b981 !important;
  font-weight: bold;
}

.custom-switch .el-switch__label.is-inactive {
  color: #ff4d4f !important;
  font-weight: bold;
}

/* 全屏居中弹窗样式 */
.fullscreen-center-dialog {
  display: flex !important;
  align-items: center;
  justify-content: center;
}

.fullscreen-center-dialog .el-dialog {
  margin: 0 !important;
  top: 50% !important;
  transform: translateY(-50%) !important;
}

@keyframes pulse {
  0% {
    transform: translateX(calc(var(--switch-width) - var(--switch-height)))
      scale(1);
  }
  50% {
    transform: translateX(calc(var(--switch-width) - var(--switch-height)))
      scale(1.1);
  }
  100% {
    transform: translateX(calc(var(--switch-width) - var(--switch-height)))
      scale(1);
  }
}

.project-table {
  min-height: 40vh;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin: 30px;
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f8fafc;
  border-bottom: 1px solid #ebeef5;
}
.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.create-button {
  margin-left: 12px;
  background: var(--el-color-primary);
  background: linear-gradient(135deg, #1e5799 0%, #2989d8 100%);
  border: none;
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.create-button:hover {
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(41, 137, 216, 0.3);
}

.page-container {
  position: relative;
  min-height: 78vh;
  padding: 20px;
}

.loading-overlay {
  position: absolute; /* 相对于main-card定位 */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10; /* 确保覆盖卡片内容 */
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3a7bb8;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.loading-text {
  font-size: 16px;
  color: #3a7bb8;
}
</style>
